package com.example.user.customviewdemo.layoutanimation.gridlayoutanimation;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;

import com.example.user.customviewdemo.R;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;

public class GridLayoutAnimationActivity extends AppCompatActivity {

    @Bind(R.id.gridview)
    GridView gridview;
    @Bind(R.id.add_grid_data_button)
    Button addGridDataButton;

    private ArrayList<String> data = new ArrayList<>();
    private GridAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_grid_layout_animation);
        ButterKnife.bind(this);

        addData();
        adapter = new GridAdapter(this);
        adapter.setData(data);

        gridview.setAdapter(adapter);


        addGridDataButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addData();
                adapter.notifyDataSetChanged();
            }
        });



    }

    private void addData(){
        for (int i = 0;i<20;i++){
            data.add("王"+i);
        }
    }

    private static class GridAdapter extends BaseAdapter{

        ArrayList<String> data = new ArrayList<>();
        private Context context;
        public GridAdapter(Context context){
            this.context = context;
        }

        public void setData(ArrayList<String> data){
            this.data = data;
            notifyDataSetChanged();
        }
        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return getItem(position).hashCode();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if(convertView == null){
                convertView = LayoutInflater.from(context).inflate(android.R.layout.simple_list_item_1,null);
            }
            ((TextView)convertView).setText(data.get(position));

            return convertView;
        }
    }
}
